package net.keebook.webapp.ws;

import java.io.IOException;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import net.keebook.webapp.bean.OpenIdBean;
import net.keebook.webapp.dao.SettingDao;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.entity.User.LoginMethod;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.Messages;
import net.keebook.webapp.util.SettingId;
import net.keebook.webapp.util.oauth.OpenIdCredentials;


@Path("/openid")
@Stateless
public class OpenIdService extends WebService {
	@EJB
	private SettingDao settingDao;
	@EJB
	private OpenIdBean openIdBean;
	
	@GET
	public void verify(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
		String root = getSettingDao().get(SettingId.PUBLIC_URL).getValue();
		if (!root.endsWith("/")) {
			root += "/";
		}
		
		HttpSession httpSession = request.getSession(true);
		SessionModel sessionModel = SessionModel.getInstance(httpSession);
		
		OpenIdCredentials credentials = getOpenIdBean().verify(sessionModel, request);
		if (credentials == null) {
			response.sendRedirect(root + "login.xhtml?msg="+Messages.LOGIN_FAILED);
			return;
		}
		
		User user = getUserDao().getUserByOauthId(credentials.getIdentifier());
		
		if (user == null) {
			String systemTimeZoneId = getSettingDao().get(SettingId.SYSTEM_TIMEZONE).getValue();
			
			user = new User();
			user.setEmail(credentials.getEmail());
			user.setName(credentials.getName());
			user.setTimezone(systemTimeZoneId);
			user.setOauthId(credentials.getIdentifier());
			user.setLoginMethod(LoginMethod.OPENID);
			getUserDao().store(user);
		}
		
		sessionModel.clear();
		sessionModel.setUserId(user.getId());
		
		response.sendRedirect(root + "index.xhtml");
		
	}

	public SettingDao getSettingDao() {
		return settingDao;
	}

	public void setSettingDao(SettingDao settingDao) {
		this.settingDao = settingDao;
	}

	public OpenIdBean getOpenIdBean() {
		return openIdBean;
	}

	public void setOpenIdBean(OpenIdBean openIdBean) {
		this.openIdBean = openIdBean;
	}
}
